// Package alertconverter provides functions to convert alerts from different sources
// to the unified AlertData format used by the system.
package alertconverter

import (
	"strings"
	"v2/model"
)

// SkyWalkingAlert represents the alert format from SkyWalking
type SkyWalkingAlert struct {
	Scope     string            `json:"scope"`
	Name      string            `json:"name"`
	Id        string            `json:"id"`
	Message   string            `json:"message"`
	StartTime int64             `json:"startTime"`
	AlarmType string            `json:"alarmType"`
	Period    int               `json:"period"`
	CauseType string            `json:"causeType"`
	Tags      map[string]string `json:"tags"`
}

// SkyWalkingTextAlert represents the text format alert from SkyWalking
type SkyWalkingTextAlert struct {
	MsgType string                `json:"msgtype"`
	Text    SkyWalkingTextContent `json:"text"`
}

// SkyWalkingTextContent represents the text content
type SkyWalkingTextContent struct {
	Content string `json:"content"`
}

// ConvertSkyWalkingAlert converts a SkyWalking alert to the unified AlertData format
func ConvertSkyWalkingAlert(skywalkingAlert SkyWalkingAlert) model.AlertData {
	severity := 2 // 默认为警告级别
	if skywalkingAlert.AlarmType == "CRITICAL" {
		severity = 1 // 紧急
	} else if skywalkingAlert.AlarmType == "WARNING" {
		severity = 3 // 警告
	}

	// 将标签转换为统一格式
	tags := make([]string, 0, len(skywalkingAlert.Tags))
	tagsMap := make(map[string]string)
	for k, v := range skywalkingAlert.Tags {
		tags = append(tags, k+"="+v)
		tagsMap[k] = v
	}

	// 确保必要的标签存在
	if skywalkingAlert.Scope != "" {
		tagsMap["scope"] = skywalkingAlert.Scope
	}
	if skywalkingAlert.Name != "" {
		tagsMap["name"] = skywalkingAlert.Name
	}
	if skywalkingAlert.Id != "" {
		tagsMap["id"] = skywalkingAlert.Id
	}
	if skywalkingAlert.CauseType != "" {
		tagsMap["cause_type"] = skywalkingAlert.CauseType
	}

	// 构建标签数组
	tags = make([]string, 0, len(tagsMap))
	for k, v := range tagsMap {
		tags = append(tags, k+"="+v)
	}

	return model.AlertData{
		ID:            hashStringToInt(skywalkingAlert.Id),
		Cate:          "skywalking",
		RuleName:      skywalkingAlert.Name,
		RuleNote:      skywalkingAlert.Message,
		TriggerTime:   skywalkingAlert.StartTime / 1000, // SkyWalking使用毫秒时间戳
		Severity:      severity,
		Tags:          tags,
		TagsMap:       tagsMap,
		FormattedTime: getCurrentFormattedTime(),
	}
}

// ConvertSkyWalkingTextAlert converts a SkyWalking text alert to the unified AlertData format
func ConvertSkyWalkingTextAlert(textAlert SkyWalkingTextAlert) model.AlertData {
	// 直接使用文本内容作为规则名称和备注
	ruleName := textAlert.Text.Content

	// 如果内容太长，截取前100个字符作为规则名称
	if len(ruleName) > 100 {
		ruleName = ruleName[:100] + "..."
	}

	// 构建标签
	tagsMap := make(map[string]string)
	tagsMap["content"] = textAlert.Text.Content
	tagsMap["source"] = "skywalking"

	tags := make([]string, 0, len(tagsMap))
	for k, v := range tagsMap {
		tags = append(tags, k+"="+v)
	}

	// 生成一个基于内容的ID
	id := hashStringToInt(textAlert.Text.Content)

	return model.AlertData{
		ID:            id,
		Cate:          "skywalking",
		RuleName:      ruleName,
		RuleNote:      textAlert.Text.Content,
		GroupName:     "SkyWalking监控",
		Cluster:       "未知集群",
		TriggerTime:   getCurrentTimestamp(),
		Severity:      2,   // 默认警告级别
		TriggerValue:  "1", // 默认触发值
		Tags:          tags,
		TagsMap:       tagsMap,
		FormattedTime: getCurrentFormattedTime(),
	}
}

// extractRuleNameFromContent 从内容中提取规则名称
func extractRuleNameFromContent(content string) string {
	// 尝试提取关键信息作为规则名称
	lines := strings.Split(content, "\n")
	if len(lines) > 0 {
		// 使用第一行作为规则名称，去除前缀
		firstLine := strings.TrimSpace(lines[0])
		if strings.Contains(firstLine, ":") {
			parts := strings.SplitN(firstLine, ":", 2)
			if len(parts) > 1 {
				return strings.TrimSpace(parts[1])
			}
		}
		return firstLine
	}

	// 默认返回内容的前100个字符
	if len(content) > 100 {
		return content[:100] + "..."
	}
	return content
}
